package com.volcreate.inn.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.volcreate.inn.mapper.CommentMapper;
import com.volcreate.inn.po.Comment;
import com.volcreate.inn.service.ICommentService;
import com.volcreate.inn.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zxc
 * @since 2020-08-23
 */
@Service
public class CommentService extends ServiceImpl<CommentMapper, Comment> implements ICommentService {


    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private UserService userService;

    private static final String pattern = "@[\u4e00-\u9fa5\\w]+ :";
    private static final Pattern p = Pattern.compile(pattern);


    @Override
    public List<CommentVO> listByBlogIdAndIsRootComment(Long id) {
        List<CommentVO> commentVOS = commentMapper.selectByBlogIdAndIsRootComment(id);
        findAtForNickname(commentVOS);
        return commentVOS;
    }


    public void findAtForNickname(List<CommentVO> commentVOS) {
        for (CommentVO commentVO : commentVOS) {
            List<CommentVO> replyComments = commentVO.getReplyComments();
            for (CommentVO replyComment : replyComments) {
                Matcher m = p.matcher(replyComment.getContent());
                if (m.find()) {
                    String nicckname = m.group().substring(1, m.end() - 2);
                    String s = userService.returnSpaceByNickname(nicckname);
                    if (s != null) {
                        replyComment.setContent("<a href=\"" + s + "\">@" + nicckname + "</a> :" + replyComment.getContent().substring(m.end()));
                    }
                }
            }
        }

    }
}
